Working with Forms and Validation
In this section, we’ll cover how to interact with form elements, capture input values, and add validation to ensure data is entered correctly. Understanding forms and validation is essential for creating functional, user-friendly web applications.
Accessing Form Elements and Retrieving Values
Form elements, like <input>
, <textarea>
, and <select>
, allow users to enter data. JavaScript makes it easy to retrieve these values and use them for various purposes.
-
Basic Form Structure
<form id="user-form">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required>
<label for="age">Age:</label>
<input type="number" id="age" name="age" required>
<button type="submit">Submit</button>
</form>
<p id="output"></p> -
JavaScript Code to Capture Input Values
const userForm = document.getElementById("user-form");
const output = document.getElementById("output");
userForm.addEventListener("submit", (event) => {
event.preventDefault(); // Prevent the form from refreshing the page
// Retrieve values from form inputs
const username = document.getElementById("username").value;
const age = document.getElementById("age").value;
output.textContent = `Username: ${username}, Age: ${age}`;
});Explanation: When the form is submitted,
event.preventDefault()
stops the default form submission, allowing us to capture and display the form data instead.
Adding Basic Validation
JavaScript validation checks help ensure users enter the correct type of information. Validation can be as simple as ensuring a field isn’t empty or as complex as verifying email or password formats.
-
Validating Input Values in JavaScript
userForm.addEventListener("submit", (event) => {
event.preventDefault();
const username = document.getElementById("username").value;
const age = document.getElementById("age").value;
if (username === "") {
output.textContent = "Username is required!";
return;
}
if (age < 1 || age > 120) {
output.textContent = "Please enter a valid age between 1 and 120.";
return;
}
output.textContent = `Username: ${username}, Age: ${age}`;
});Explanation: This code checks if the username field is empty and if the age is within a reasonable range. If validation fails, an error message is displayed.
Advanced Validation Using Regular Expressions
For fields like email addresses, regular expressions (regex) are useful to match specific patterns.
-
Email Validation Example
<form id="email-form">
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<button type="submit">Submit</button>
</form>
<p id="email-output"></p>const emailForm = document.getElementById("email-form");
const emailOutput = document.getElementById("email-output");
emailForm.addEventListener("submit", (event) => {
event.preventDefault();
const email = document.getElementById("email").value;
const emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/;
if (!emailPattern.test(email)) {
emailOutput.textContent = "Please enter a valid email address.";
} else {
emailOutput.textContent = `Email: ${email}`;
}
});Explanation: The
emailPattern
regex ensures the email is in a valid format. If the email doesn’t match the pattern, an error message displays; otherwise, it confirms the email.
Showing Real-Time Feedback
Real-time feedback lets users know immediately if their input is valid, improving user experience.
-
Adding Real-Time Validation
const ageInput = document.getElementById("age");
ageInput.addEventListener("input", () => {
const age = ageInput.value;
if (age < 1 || age > 120) {
output.textContent = "Please enter a valid age between 1 and 120.";
} else {
output.textContent = "";
}
});Explanation: As the user types, this code checks if the age input is valid. If not, a message appears; once it’s valid, the message clears.